<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useSocketStore } from '@/stores/socket.js'
import Peer from 'peerjs'
import { Socket } from 'socket.io-client'
import { hostUrl, port } from '@/utils/express/express.js'
// import { ElText } from "element-plus";
const socketIo = useSocketStore()
const socket = socketIo.socket
let peerId = null
let stream = null
const anotherDom = ref(null)
const videoDom = ref(null)
const callState = ref(false)
const peer = new Peer({
  host: hostUrl,
  port: port,
  path: '/',
  pingInterval: 5000
})
peer.on('open', function (id) {
  console.log('PeerID是', id)
  socket.emit('saveId', id)
  peerId = id
})
const getPermissions = async () => {
  try {
    return await navigator.mediaDevices.getUserMedia({ audio: true, video: true })
  } catch (error) {
    if (error.name === 'NotFoundError') {
      console.log('没有在您的电脑上找到语音或视频设备', error)
    } else console.log('请同意授权')
  }
}
onMounted(async () => {
  stream = await getPermissions()
  videoDom.value.srcObject = stream
  videoDom.value.play()
})
const callinvite = () => {
  socket.emit('test')
  socket.emit('getId', peerId, (e) => {
    console.log('打电话')
    console.log('对方电话id', e)
    let call = peer.call(e, stream)
    call.on('stream', (remoteStream) => {
      anotherDom.value.srcObject = remoteStream
      anotherDom.value.play()
      console.log('对方成功回应')
      callState.value = true
    })
  })
}
peer.on('call', function (call) {
  console.log('接听电话')
  callState.value = true
  call.answer(stream)
  call.on('stream', function (stream) {
    anotherDom.value.srcObject = stream
    anotherDom.value.play()
  })
})
</script>

<template>
  <button @click="callinvite">拨打</button>
  <!-- <button>接通</button> -->
  <div class="videoMain">
    <video muted :class="callState ? 'videoSmall' : 'videoBig'" ref="videoDom"></video>
    <video
      :style="{ display: callState ? 'block' : 'none' }"
      :class="!callState ? 'videoSmall' : 'videoBig'"
      ref="anotherDom"
    ></video>
  </div>
</template>

<style lang="scss" scoped>
.videoBig {
  width: 780px;
}
.videoSmall {
  position: absolute;
  width: 200px;
  right: 0;
  bottom: 0;
}
.videoMain {
  position: relative;
  width: 780px;
}
</style>
